package com.hsq.androidproject.ui;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.example.lenovo.androidproject3.R;
import com.hsq.androidproject.entity.UserBean;
import com.hsq.androidproject.ui.Users.ShowUsers;
import com.hsq.androidproject.weight.weibo.AccessTokenKeeper;
import com.hsq.androidproject.weight.weibo.Constants;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.tencent.connect.UserInfo;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import static com.tencent.open.utils.Global.getContext;

public class LoginActivity extends FragmentActivity {
    private Button qqLogin, wbLogin;
    private static final String APPID = "1105975207";
    private Tencent mTencent; //qq主操作对象
    private IUiListener loginListener; //授权登录监听器
    private IUiListener userInfoListener; //获取用户信息监听器
    private UserInfo userInfo; //qq用户信息
    private AuthInfo mAuthInfo;
    private SsoHandler mSsoHandler;
    private Oauth2AccessToken mAccessToken;
    public static UserBean user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initViews();
        initQQ();
        initListerens();
    }

    private void initListerens() {
        qqLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Loginstate = 1;
                qqlogin();

            }
        });
        wbLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Loginstate = 0;
                weiboLogin();
            }
        });
    }

    private void initViews() {
        qqLogin = (Button) findViewById(R.id.btn_qqlogin);
        wbLogin = (Button) findViewById(R.id.btn_wblogin);
    }

    private void weiboLogin() {
        mAuthInfo = new AuthInfo(getContext(), Constants.APP_KEY, Constants.REDIRECT_URL, Constants.SCOPE);
        mSsoHandler = new SsoHandler(LoginActivity.this, mAuthInfo);
        mSsoHandler.authorize(new WeiboAuthListener() {
            @Override
            public void onComplete(Bundle values) {
                // 从 Bundle 中解析 Token
                mAccessToken = Oauth2AccessToken.parseAccessToken(values);
                if (mAccessToken.isSessionValid()) {
                    // 保存 Token 到 SharedPreferences
                    AccessTokenKeeper.writeAccessToken(LoginActivity.this, mAccessToken);
                    Log.d("TAG", "onComplete: ---------" + mAccessToken);

                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            UsersAPI usersAPI = new UsersAPI(LoginActivity.this, Constants.APP_KEY, mAccessToken);
                            usersAPI.show(Long.valueOf(mAccessToken.getUid()), new SinaRequestListener());
                        }
                    }).start();

                } else {
                    // 当您注册的应用程序签名不正确时，就会收到 Code，请确保签名正确
                    String code = values.getString("code", "");
                }
            }

            @Override
            public void onWeiboException(WeiboException e) {


            }

            @Override
            public void onCancel() {
            }
        });
    }

    private void init() {

    }

    private void initQQ() {
        mTencent = Tencent.createInstance(APPID,this);
        //要所有权限，不然会再次申请增量权限，这里不要设置成get_user_info,add_t

        loginListener = new IUiListener() {
            @Override
            public void onComplete(Object value) {
                if (value == null) {
                    return;
                }

                try {
                    JSONObject jo = (JSONObject) value;

                    int ret = jo.getInt("ret");

                    System.out.println("json=" + String.valueOf(jo));
                    //I/System.out: json={"ret":0,"pay_token":"D13357167DC8FBB38D3C1188CBE969EB",
                    // "pf":"desktop_m_qq-10000144-android-2002-",
                    // "query_authority_cost":373,
                    // "authority_cost":0,
                    // "openid":"CD97E055295EEA79D322BDEDEC9B11EE",
                    // "expires_in":7776000,
                    // "pfkey":"074f7b8dc642f889a05a804ec33c8187",
                    // "msg":"",
                    // "access_token":"966EFD23F14CDB1CC0D483413C0A24E9",
                    // "login_cost":166}
                    if (ret == 0) {

                        String openID = jo.getString("openid");
                        String accessToken = jo.getString("access_token");
                        String expires = jo.getString("expires_in");
                        mTencent.setOpenId(openID);
                        mTencent.setAccessToken(accessToken, expires);
                    }
                } catch (Exception e) {
                    System.out.println("" + e);
                }
            }

            @Override
            public void onError(UiError uiError) {
            }

            @Override
            public void onCancel() {
            }
        };


        userInfoListener = new IUiListener() {
            @Override
            public void onComplete(Object arg0) {
                // TODO Auto-generated method stub
                if (arg0 == null) {
                    return;
                }

                try {
                    JSONObject jo = (JSONObject) arg0;
                    //{"is_yellow_year_vip":"0","ret":0,
                    // "figureurl_qq_1":"http:\/\/q.qlogo.cn\/qqapp\/1105923395\/CD97E055295EEA79D322BDEDEC9B11EE\/40",
                    // "figureurl_qq_2":"http:\/\/q.qlogo.cn\/qqapp\/1105923395\/CD97E055295EEA79D322BDEDEC9B11EE\/100",
                    // "nickname":"　A-",
                    // "yellow_vip_level":"0",
                    // "is_lost":0,"msg":"",
                    // "city":"朝阳",
                    // "figureurl_1":"http:\/\/qzapp.qlogo.cn\/qzapp\/1105923395\/CD97E055295EEA79D322BDEDEC9B11EE\/50",
                    // "vip":"0","level":"0",
                    // "figureurl_2":"http:\/\/qzapp.qlogo.cn\/qzapp\/1105923395\/CD97E055295EEA79D322BDEDEC9B11EE\/100","
                    // province":"北京",
                    // "is_yellow_vip":"0",
                    // "gender":"男",
                    // "figureurl":"http:\/\/qzapp.qlogo.cn\/qzapp\/1105923395\/CD97E055295EEA79D322BDEDEC9B11EE\/30"}
                    System.out.println("info-----------------------=" + String.valueOf(jo));
                    int ret = jo.getInt("ret");
                    String nickName = jo.getString("nickname");
                    String gender = jo.getString("gender");
                    String img = jo.getString("figureurl_qq_2");
                    user = new UserBean(null, nickName, img);
                    Intent intent=new Intent(LoginActivity.this,ShowUsers.class);
                    intent.putExtra("user",user);
                    startActivity(intent);
                    LoginActivity.this.finish();

                } catch (Exception e) {

                }
            }

            @Override
            public void onError(UiError uiError) {

            }

            @Override
            public void onCancel() {

            }
        };


    }

    private void qqlogin() {
        //如果session无效，就开始登录
        if (!mTencent.isSessionValid()) {
            //开始qq授权登录
            mTencent.login(this, "all", loginListener);
        }
    }

    int Loginstate = 0;//用来判断是微博登录还是QQ登录

    //登陆后返回
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Loginstate == 0) {
            super.onActivityResult(requestCode, resultCode, data);
            if (mSsoHandler != null) {
                mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
            System.out.print("微博登录");
        } else {
            Tencent.onActivityResultData(requestCode, resultCode, data, loginListener);
            userInfo = new UserInfo(getContext(), mTencent.getQQToken());
            userInfo.getUserInfo(userInfoListener);

        }
    }

    public class SinaRequestListener implements RequestListener { //新浪微博请求接口
        @Override
        public void onComplete(String response) {// TODO Auto-generated method stub
            try {
                JSONObject jsonObject = new JSONObject(response);
                String idStr = jsonObject.getString("idstr");// 唯一标识符(uid)
                String name = jsonObject.getString("name");// 姓名
                String avatarHd = jsonObject.getString("avatar_hd");// 头像
                Log.d("TAG", "onComplete: --------------" + avatarHd);
                user = new UserBean(idStr, name, avatarHd);
                LoginActivity.this.finish();

                //    Message message = handler.obtainMessage();
                //   message.what = 1;
                //  handler.sendMessage(message);
            } catch (JSONException e) {// TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {// TODO Auto-generated method stubToast.makeText(context, "Auth exception : " + e.getMessage(),Toast.LENGTH_LONG).show();
            Log.i("mylog", "Auth exception : " + e.getMessage());
        }
    }

}
